Algorithm: Breadth-First Search (BFS)
BFS is a fundamental graph traversal algorithm used to explore a graph systematically, finding the shortest path (in terms of edges) from a source node to all other reachable nodes. It guarantees nodes are processed in increasing order of distance.
BFS Mechanism
- Initialization: For every node , set `color` to `WHITE` (unvisited), distance , and parent .
- Source Setup: Set the source to `GRAY` (discovered), , and initialize a FIFO Queue with .
- Exploration Loop: While is not empty, dequeue node :
- For every neighbor of :
- If is `WHITE`:
- Set to `GRAY`.
- (Level increment).
- (Record parent).
- Enqueue .
- If is `WHITE`:
- Once all neighbors are processed, mark as `BLACK` (fully explored).
- For every neighbor of :
Key BFS Properties & Use Cases
The Power of the Queue: BFS fundamentally relies on the FIFO property of the Queue. This ensures that the algorithm visits all nodes at distance from the source before visiting any nodes at distance . This level-by-level exploration guarantees unweighted shortest paths.
Connectivity and Levels:
- Levels: The value represents the minimum number of edges needed to reach from . This is the shortest path length.
- BFS Tree: The set of parent pointers implicitly defines the BFS Tree, which is a subgraph containing only shortest-path edges from .
- Use Cases: Finding shortest paths (unweighted), networking broadcast, web crawlers (finding minimum link depth), and garbage collection (reachable objects).
BFS Complexity Analysis
BFS is highly efficient, examining every vertex and edge exactly once, provided the graph is represented using an Adjacency List.
| Metric | Cost (Adjacency List) | Explanation |
|---|---|---|
| Initialization | Processing all vertices once. | |
| Queue Operations | Each vertex is enqueued and dequeued exactly once. | |
| Edge Examination | The total time spent scanning adjacency lists is proportional to the number of edges . | |
| Total Runtime | Linear time complexity relative to the size of the graph. |
1. Which data structure is essential for implementing the level-by-level exploration of Breadth-First Search?
2. What is the time complexity of BFS on a graph with vertices and edges, when using an adjacency list?
3. BFS is guaranteed to find the shortest path in which type of graph?
4. After running BFS from a source , which outputs are needed to reconstruct the shortest paths and distances?